package com.ruoyi.ucar.util;


import java.io.*;
import java.util.Base64;
import java.util.concurrent.TimeUnit;

public class PuppeteerScreenshotUtil {
    private static final String NODE_SCRIPT = "longpage-screenshot.js";

    public static void captureFullPage(String url, String outputPath,String height)
            throws IOException, InterruptedException {

        ProcessBuilder pb = new ProcessBuilder(
                "/root/.nvm/versions/node/v20.19.4/bin/node", NODE_SCRIPT, url, height
        );
        pb.directory(new File("/aiit/ucarscreenshot")); // 关键：设置工作目录

        pb.redirectErrorStream(true);

        Process process = pb.start();
        StringBuilder result = new StringBuilder();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {

            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            if (!process.waitFor(45, TimeUnit.SECONDS)) {
                process.destroyForcibly();
                throw new RuntimeException("执行超时");
            }

            byte[] imageData = Base64.getDecoder().decode(result.toString());
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                fos.write(imageData);
            }
        }
    }

    public static void main(String[] args) {
        try {
            PuppeteerScreenshotUtil.captureFullPage(
                    "https://bgjk6.chexinmeng.com/cxsh/agentReportxbqg2?data=D06C829AEDE9460654BE8F2C2F46F621CE3CDF702DF697E0177C7D65B4E232DD5A9AB84098962FAEC0BD2F04116B3439F7CD9FB1A8E8151414534AB9B47D2A864C9F69F7B81C2741D93420845A15444E9499055325B5AF0C1D5F289EB6F0274EB86FCE341A7B5566BED100A5550D8041256E3F1E31D5674982C37C9C1C89CDE4B0ED0C422D92DA1D3BC2C042D733C8E2",
                    "D:\\project\\Test\\images\\fullpage.png","9500"
            );
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


